import { defineStore } from 'pinia'
import * as ticketApi from '@/api/ticket'
import type { Ticket, TicketFilter, CreateTicketDto, UpdateTicketDto, TicketStatistics } from '@/api/ticket'

interface TicketState {
  tickets: Ticket[]
  currentTicket: Ticket | null
  statistics: TicketStatistics | null
  total: number
  loading: boolean
  error: string | null
  filter: TicketFilter
}

export const useTicketStore = defineStore('ticket', {
  state: (): TicketState => ({
    tickets: [],
    currentTicket: null,
    statistics: null,
    total: 0,
    loading: false,
    error: null,
    filter: {
      page: 1,
      pageSize: 20,
      status: [],
      priority: [],
      type: [],
      search: '',
    },
  }),

  getters: {
    // 按状态分组的工单
    ticketsByStatus: (state) => {
      return {
        open: state.tickets.filter((t) => t.status === 'open'),
        in_progress: state.tickets.filter((t) => t.status === 'in_progress'),
        pending: state.tickets.filter((t) => t.status === 'pending'),
        resolved: state.tickets.filter((t) => t.status === 'resolved'),
        closed: state.tickets.filter((t) => t.status === 'closed'),
      }
    },

    // 按优先级分组的工单
    ticketsByPriority: (state) => {
      return {
        critical: state.tickets.filter((t) => t.priority === 'critical'),
        high: state.tickets.filter((t) => t.priority === 'high'),
        medium: state.tickets.filter((t) => t.priority === 'medium'),
        low: state.tickets.filter((t) => t.priority === 'low'),
      }
    },

    // SLA 超期的工单
    breachedTickets: (state) => {
      return state.tickets.filter((t) => t.sla?.isBreached)
    },
  },

  actions: {
    // 获取工单列表
    async fetchTickets(filter?: TicketFilter) {
      this.loading = true
      this.error = null

      try {
        if (filter) {
          this.filter = { ...this.filter, ...filter }
        }

        const response = await ticketApi.getTickets(this.filter)
        this.tickets = response.data || []
        this.total = response.pagination?.total || 0
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to fetch tickets'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取工单详情
    async fetchTicketById(id: string) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.getTicketById(id)
        this.currentTicket = response
        return this.currentTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to fetch ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建工单
    async createTicket(data: CreateTicketDto) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.createTicket(data)
        const newTicket = response.ticket
        this.tickets.unshift(newTicket)
        this.total += 1
        return newTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to create ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新工单
    async updateTicket(id: string, data: UpdateTicketDto) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.updateTicket(id, data)
        const updatedTicket = response.data.data

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets[index] = updatedTicket
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to update ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新工单状态
    async updateTicketStatus(id: string, status: Ticket['status'], reason?: string) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.updateTicketStatus(id, status, reason)
        const updatedTicket = response.data.data

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets[index] = updatedTicket
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to update status'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 分配工单
    async assignTicket(id: string, assignedTo: string) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.assignTicket(id, assignedTo)
        const updatedTicket = response.data.data

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets[index] = updatedTicket
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to assign ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 添加评论
    async addComment(id: string, content: string, isInternal: boolean = false) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.addComment(id, content, isInternal)
        const updatedTicket = response.data.data

        if (this.currentTicket?._id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to add comment'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 解决工单
    async resolveTicket(id: string, solution: string, rootCause?: string, preventiveMeasures?: string) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.resolveTicket(id, solution, rootCause, preventiveMeasures)
        const updatedTicket = response.data.data

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets[index] = updatedTicket
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to resolve ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 关闭工单
    async closeTicket(id: string) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.closeTicket(id)
        const updatedTicket = response.data.data

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets[index] = updatedTicket
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = updatedTicket
        }

        return updatedTicket
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to close ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除工单
    async deleteTicket(id: string) {
      this.loading = true
      this.error = null

      try {
        await ticketApi.deleteTicket(id)

        const index = this.tickets.findIndex((t) => t.id === id)
        if (index !== -1) {
          this.tickets.splice(index, 1)
          this.total -= 1
        }

        if (this.currentTicket?.id === id) {
          this.currentTicket = null
        }
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to delete ticket'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取统计信息
    async fetchStatistics(filter?: Partial<TicketFilter>) {
      this.loading = true
      this.error = null

      try {
        const response = await ticketApi.getTicketStatistics(filter)
        this.statistics = response.data.data
        return this.statistics
      } catch (error: any) {
        this.error = error.response?.data?.message || error.message || 'Failed to fetch statistics'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 设置过滤条件
    setFilter(filter: Partial<TicketFilter>) {
      this.filter = { ...this.filter, ...filter }
    },

    // 重置过滤条件
    resetFilter() {
      this.filter = {
        page: 1,
        pageSize: 20,
        status: [],
        priority: [],
        type: [],
        search: '',
      }
    },

    // 清除当前工单
    clearCurrentTicket() {
      this.currentTicket = null
    },

    // 清除错误
    clearError() {
      this.error = null
    },
  },
})
